import z from "zod";

// 用户登录验证schema
export const LoginRequestSchema = z.object({
  mobile: z.string().regex(/^1[3-9]\d{9}$/, "手机号格式不正确"), // 校验11位手机号
  password: z.string().min(6, "密码至少6位").max(20, "密码最多20位"), // 校验密码长度
});

export type LoginRequestDTO = z.infer<typeof LoginRequestSchema>;

// 用户注册验证schema
export const RegisterRequestSchema = z.object({
  name: z.string().min(1, "请输入用户名").max(20, "用户名最多20位"),
  mobile: z.string().regex(/^1[3-9]\d{9}$/, "请输入正确的手机号"),
  password: z.string().min(6, "密码至少6位").max(20, "密码最多20位"),
  role: z.enum(["normal", "admin"]).optional().default("normal"),
});

export type RegisterRequestDTO = z.infer<typeof RegisterRequestSchema>;

// 用户更新验证schema
export const UpdateUserRequestSchema = z
  .object({
    name: z
      .string()
      .min(1, "请输入用户名")
      .max(20, "用户名最多20位")
      .optional(),
    mobile: z
      .string()
      .regex(/^1[3-9]\d{9}$/, "请输入正确的手机号")
      .optional(),
    password: z
      .string()
      .min(6, "密码至少6位")
      .max(20, "密码最多20位")
      .optional(),
    role: z.enum(["normal", "admin"]).optional(),
    isDisable: z.boolean().optional(),
  })
  .refine(
    (data) => {
      // 至少提供一个要更新的字段
      return Object.values(data).some((value) => value !== undefined);
    },
    {
      message: "至少提供一个要更新的字段",
    }
  );

export type UpdateUserRequestDTO = z.infer<typeof UpdateUserRequestSchema>;

const passwordSchema = z
  .string()
  .min(3, "密码至少需要3位字符")
  .max(20, "密码不能超过20位字符")
  .regex(/^[a-zA-Z0-9_]+$/, "密码只能包含字母、数字和下划线");

export const updatePasswordRequestSchema = z.object({
  oldPassword: passwordSchema,
  newPassword: passwordSchema,
});

export type UpdatePasswordRequestDTO = z.infer<
  typeof updatePasswordRequestSchema
>;
